﻿using System;
using System.Web.Security;
using System.Web.UI.WebControls;

namespace rpxlogindemo.pages
{
    public partial class _Default : BasePage
    {
        private const int pageSize = 20;
        private int pageNumber = 1;

        protected void Page_Load(object sender, EventArgs e)
        {
            this.LoadPageNumber();
        }

        private void LoadPageNumber()
        {
            if (!string.IsNullOrEmpty(Request.QueryString["p"]))
            {
                if (!int.TryParse(Request.QueryString["p"], out this.pageNumber))
                    this.pageNumber = 1;

            }
        }

        public override void DataBind()
        {
            int totalRecords = 0;
            // use the the standard Membership.GetAllUsers call
            // this will return a MembershipUserCollection ostensibly
            // of MembershipUser objects.
            // However we know they're really OpenIdMembershipUser objects
            // containing our own extra properties which we can cast out to in a minute. (In lvUsers_ItemDataBound.)
            this.lvUsers.DataSource = Membership.GetAllUsers(this.pageNumber - 1, _Default.pageSize, out totalRecords);

            base.DataBind();

            this.RenderPaging(totalRecords);
        }

        private void RenderPaging(int totalRecords)
        {
            this.litRecords.Text = String.Format("{0} users", totalRecords);
            if (this.pageNumber > 1)
            {
                this.hypPrevious.NavigateUrl = String.Format(".?p={0}", this.pageNumber - 1);
            }
            if (this.pageNumber < ((float)totalRecords / (float)_Default.pageSize))
            {
                this.hypNext.NavigateUrl = String.Format(".?p={0}", this.pageNumber + 1);
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
        }

        protected void lvUsers_ItemDataBound(object sender, System.Web.UI.WebControls.ListViewItemEventArgs e)
        {
            // cast our "MembershipUser" to a OpenIdMembershipUser in order to access its extra properties
            var openIdMembershipUser = ((ListViewDataItem)e.Item).DataItem as rpxnow_library.membership.OpenIdMembershipUser;
            if (openIdMembershipUser != null)
            {
                ((Image)e.Item.FindControl("imgPhoto")).ImageUrl = openIdMembershipUser.photo;
                ((HyperLink)e.Item.FindControl("hypPhoto")).NavigateUrl = "~/Users/User.aspx?u=" + Server.UrlEncode(openIdMembershipUser.UserName);
                ((HyperLink)e.Item.FindControl("hypName")).NavigateUrl = "~/Users/User.aspx?u=" + Server.UrlEncode(openIdMembershipUser.UserName);
            }
        }
    }
}